package com.example.controller;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.example.bean.ActionResult;
import com.example.bean.ReleaseNoteBean;
import com.example.service.ReleaseNoteService;
import com.example.util.Host;
import com.example.util.TimeUtil;

@Controller
@RequestMapping("/")
public class ReleaseNoteController {

    protected Log log = LogFactory.getLog(getClass());

    // can not inject, get error:java.lang.IllegalStateException: Failed to load
    // ApplicationContext
    // @Autowired
    // private ServletContext servletContext;

    @Value("${siteDisplay}")
    private String siteDisplay;
    @Value("${websiteVesion}")
    private String websiteVesion;

    @Autowired // (name = "releaseNoteServiceImpl")
    private ReleaseNoteService releaseNoteService;

    @RequestMapping(value = "ReleaseNoteAdmin.do", method = RequestMethod.GET)
    public String releaseNoteAdmin(Model model, HttpServletRequest request) throws UnknownHostException {
        InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
        String id = Host.getId(addr);
        model.addAttribute("uid", id);
        List<ReleaseNoteBean> releaseNotes = releaseNoteService.getAll();
        model.addAttribute("siteDisplay", siteDisplay);
        model.addAttribute("websiteVesion", websiteVesion);
        model.addAttribute("releaseNotes", releaseNotes);
        return "releaseNote/mdReleaseNoteAdmin";
    }

    @RequestMapping(value = "ReleaseNoteMain.do", method = RequestMethod.GET)
    public String releaseNoteMain(Model model, HttpServletRequest request) throws Exception, UnknownHostException {
        InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
        String id = Host.getId(addr);
        model.addAttribute("uid", id);
        List<ReleaseNoteBean> releaseNotes = releaseNoteService.getAll();
        model.addAttribute("siteDisplay", siteDisplay);
        model.addAttribute("websiteVesion", websiteVesion);
        model.addAttribute("releaseNotes", releaseNotes);
        return "releaseNote/mdReleaseNote";
    }

    @RequestMapping(value = "getReleaseNotesList.do", method = RequestMethod.POST)
    @ResponseBody
    public ActionResult releaseNotesList(Model model) throws Exception {
        ActionResult result = new ActionResult(true);
        List<ReleaseNoteBean> releaseNotes = releaseNoteService.getAll();
        result.setRtnVal(releaseNotes);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping(value = "editor.do", method = RequestMethod.GET)
    public String editor(Model model, @RequestParam("objId") Long objId) {
        model.addAttribute("releasenote_id", objId);
        return "releaseNote/mdReleaseNoteEditor";
    }

    @RequestMapping(value = "getReleaseNote.do", method = RequestMethod.POST)
    public @ResponseBody ActionResult getReleaseNote(Model model, @RequestParam("objId") Long objId) throws Exception {
        ActionResult result = new ActionResult(true);
        ReleaseNoteBean releasenote = releaseNoteService.getReleaseNote(objId);
        result.setRtnVal(releasenote);
        result.setSuccess(true);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "releaseNote/image/upload.do", method = RequestMethod.POST)
    public String uploadImage(HttpServletRequest req, @RequestParam(value = "guid") String guid,
            @RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
            HttpServletRequest request) throws Exception {
        String trueFileName = file.getOriginalFilename();
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        String fileName = System.currentTimeMillis() + "_" + guid + suffix;
        // String path = "C:/flawScanAnalytic/releaseNote/images";

        ServletContext servletContext = req.getServletContext();
        String path = servletContext.getRealPath("/");
        System.out.println(path);

        // ..src/main/app/data/images/xx.png(/jpg/..)
        File targetFile = new File(path, "data/images/" + fileName);

        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        try {
            file.transferTo(targetFile);
            // ImageUtil.reSize(targetFile, targetFile, 320, 320, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("url", "images/" + fileName);
        json.put("success", 1);
        json.put("message", "upload success!");

        String result = JSON.toJSONString(json);
        return result;
    }

    @RequestMapping(value = "releaeNote/updateReleaseNote.do", method = RequestMethod.POST)
    public @ResponseBody ActionResult saveReleaseNote(@RequestParam("objId") Long objId,
            @RequestParam("content") String content) throws Exception {
        ActionResult rst = new ActionResult(false);
        ReleaseNoteBean releaseNoteBean = releaseNoteService.getReleaseNote(objId);
        if (releaseNoteBean == null) {
            throw new Exception(" objid:" + objId + " not exists");
        }
        ;
        releaseNoteBean.setContent(content);
        releaseNoteService.saveReleaseNote(releaseNoteBean);
        rst.setSuccess(true);
        return rst;
    }

    @RequestMapping(value = "releaeNote/newReleaseNote.do", method = RequestMethod.POST)
    public @ResponseBody ActionResult newReleaseNote(@RequestParam("version") String version,
            @RequestParam("content") String content, @RequestParam("publishDate") String publishDT) throws Exception {
        ActionResult rst = new ActionResult(false);
        ReleaseNoteBean releaseNoteBean = new ReleaseNoteBean();
        releaseNoteBean.setVersion(version);
        releaseNoteBean.setContent(content);
        // publishDT "4/24/2021 2:38:10 PM"
        publishDT = TimeUtil.formatString(publishDT);
        releaseNoteBean.setPublishdate(publishDT);
        releaseNoteService.saveReleaseNote(releaseNoteBean);
        rst.setSuccess(true);
        return rst;
    }

    @RequestMapping(value = "releaeNote/deleteReleaseNote.do", method = RequestMethod.POST)
    public @ResponseBody ActionResult deleteReleaseNote(@RequestParam("objId") Long objId) throws Exception {
        ActionResult rst = new ActionResult(false);
        ReleaseNoteBean releaseNoteBean = releaseNoteService.getReleaseNote(objId);
        if (releaseNoteBean == null) {
            throw new Exception(" objid:" + objId + " not exists");
        }
        ;
        releaseNoteService.deleteReleaseNote(objId);
        rst.setSuccess(true);
        return rst;
    }
}
